<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <template #header>
      <el-button type="primary" size="default" :icon="Plus" @click="addTrademark">添加</el-button>
    </template>
    <!-- card body -->
    <el-table style="margin-bottom: 30px;" :data="tableData" border stripe>
      <el-table-column label="序号" align="center" type="index" width="80" />
      <el-table-column prop="tmName" label="品牌名称"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template #default="{ row }">
          <img height="100" :src="row.logoUrl">
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="warning" size="small" :icon="Edit" @click="updateTrademark(row)">修改</el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="deleteTrademark(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:page-size="limit" v-model:current-page="page" :pager-count="5"
      layout="prev, pager, next,sizes" :total="total" :page-sizes="[3, 5, 7, 9]" />
  </el-card>
  <el-dialog v-model="dialogFormVisible" :title="newTrademark.id ? '修改品牌' : '添加品牌'">
    <el-form label-width="100px" :model="newTrademark" :rules="trademarkRule" ref="ruleFormRef">
      <el-form-item label="品牌名称" prop="tmName">
        <el-input autocomplete="off" v-model="newTrademark.tmName" />
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <el-upload class="avatar-uploader" :action="`${baseUrl}/admin/product/upload`" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateOrAddTrademark">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import { ref, toRefs, onMounted, watch, reactive } from "vue"
import { Plus, Edit, Delete } from "@element-plus/icons-vue"
import { requestTrademarkList, requestPutTrademarkList, requestUpdateTrademarkList, requestDeleteTrademarkList } from "@/api/Trademark"
import type { reqTrademarkReturnRecordsType, reqTrademarkReturnItemType } from "@/api/Trademark"
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, FormRules, FormInstance } from 'element-plus'
// table的逻辑
// table的数据
const tableData = ref<reqTrademarkReturnRecordsType>([]);
// 页面逻辑
// 页面的数据和类型
interface pageDateType {
  page: number,
  limit: number,
  total: number
}
const pageDate = ref<pageDateType>({
  page: 1,
  limit: 3,
  total: 100
})
const { page, limit, total } = toRefs<pageDateType>(pageDate.value)

// 监听页码的改变重新发送请求
watch([page, limit], () => {
  // 重新发送请求
  getTrademarkList()
})

// 获取品牌列表数据
const getTrademarkList = async () => {
  const result = await requestTrademarkList({
    page: page.value,
    limit: limit.value
  })
  // 把请求回来的数据给tableDate
  tableData.value = result.records
  total.value = result.total
}
// 初始化
onMounted(() => {
  // 调用获取品牌列表的功能函数
  getTrademarkList()
});

// 弹窗逻辑
// 控制弹窗显示隐藏
const dialogFormVisible = ref(false)
const baseUrl = import.meta.env.VITE_API_URL
const newTrademark = ref<reqTrademarkReturnItemType>({
  logoUrl: "",
  tmName: "",
  id: 0
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  newTrademark.value.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 添加数据的逻辑
const addTrademark = () => {
  // 先清空上次残留的校验信息
  ruleFormRef.value?.clearValidate()
  dialogFormVisible.value = true
  newTrademark.value = {
    logoUrl: "",
    tmName: "",
    id: 0
  }
}

// 修改数据的逻辑
const updateTrademark = (row: reqTrademarkReturnItemType) => {
  // 先清空上次残留的校验信息
  ruleFormRef.value?.clearValidate()
  dialogFormVisible.value = true
  // 将row浅拷贝赋值给newTrademark
  newTrademark.value = { ...row }
}

// 新增和修改提交
// 获取form表单的实例
const ruleFormRef = ref<FormInstance>()
const updateOrAddTrademark = async () => {
  try {
    // 先进行全局校验
    await ruleFormRef.value?.validate()
    dialogFormVisible.value = false
    // 存在id即为修改,没有则为新增
    try {
      if (newTrademark.value.id) {
        await requestUpdateTrademarkList(newTrademark.value)
        ElMessage.success("修改成功")
      } else {
        await requestPutTrademarkList(newTrademark.value)
        ElMessage.success("新增成功")
        page.value = 1
      }
      // 重新发送请求
      getTrademarkList()
    } catch (e) {
      ElMessage(newTrademark.value.id ? "修改错误" : "新增错误")
    }
  } catch (e) {
    ElMessage("请填写合法的值")
  }
}

// 删除逻辑
const deleteTrademark = (id: number) => {
  ElMessageBox.confirm(
    '你真的要删除吗',
    '警告!!',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await requestDeleteTrademarkList(id)
        // 重新发送请求
        getTrademarkList()
      } catch (e) {
        ElMessage.error("删除失败")
      }
    })
    .catch(() => {
      ElMessage.info("点错了吧")
    })
}

// 表单校验规则
// 自定义表单规则函数
const checkTmNameLength = (rule: any, value: string, callback: any) => {
  if (value.length < 2 || value.length > 5) {
    callback("长度必须是2-5")
  } else {
    callback()
  }
}
const trademarkRule = reactive<FormRules>({
  tmName: [
    { required: true, message: '必须填写品牌名称', trigger: 'blur' },
    { validator: checkTmNameLength, message: '长度必须是2-5', trigger: 'blur' },
  ],
  logoUrl: [{ required: true, message: '必须上传图片', trigger: 'change' }],
})



</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>